//
//  QRCodeViewController.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/7/1.
//  Copyright © 2015年 yyz. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet weak var tabBar: UITabBar!
    
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!

    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var scanImage: UIImageView!
    
    @IBOutlet weak var resultLabel: UILabel!
    
    @IBAction func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func showMyCard(){
        navigationController?.pushViewController(QRCodeMyCardViewController(), animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tabBar.selectedItem = tabBar.items![0]
        
        setupLayers()
        setupSession()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        startAnimation()
        startScan()
    }
    
    func startScan(){
        session.startRunning()
    }
    
    func startAnimation(){
        topConstraint.constant = -heightConstraint.constant
        self.view.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }
    }
    
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        
        heightConstraint.constant = widthConstraint.constant * (item.tag == 1 ? 0.5 : 1)
        
        scanImage.layer.removeAllAnimations()
        
        startAnimation()
    }

    // MARK - 二维码扫描
    func setupSession(){
        if !session.canAddInput(inputDevice) {
            return
        }
        if !session.canAddOutput(outputData) {
            return
        }
        
        session.addInput(inputDevice)
        
        session.addOutput(outputData)
        
        outputData.metadataObjectTypes = outputData.availableMetadataObjectTypes
        
        outputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
    }
    
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        clearDrawLayer()
        
        for object in metadataObjects{
            if object is AVMetadataMachineReadableCodeObject{
                let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                
                drawCorners(codeObject)
                // readonly AVMetadataMachineReadableCodeObject only have two properties
                resultLabel.text = codeObject.stringValue
            }
        }
    }
    
    private func drawCorners(codeObject:AVMetadataMachineReadableCodeObject){
        let layer = CAShapeLayer()
        layer.lineWidth = 4.0
        layer.fillColor = UIColor.clearColor().CGColor
        layer.strokeColor = UIColor.greenColor().CGColor
        
        layer.path = creatPath(codeObject.corners).CGPath
        drawLayer.addSublayer(layer)
    }
    
    private func creatPath(corners:NSArray) -> UIBezierPath{
        let path = UIBezierPath()
        var point = CGPoint()
        var index = 0
        
        CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
        path.moveToPoint(point)
        
        while index < corners.count{
            CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
            path.addLineToPoint(point)
        }
        path.closePath()
        
        return path
    }
    
    private func clearDrawLayer(){
        if drawLayer.sublayers == nil{
            return
        }
        for sublayer in drawLayer.sublayers!{
            sublayer.removeFromSuperlayer()
        }
        
    }
    
    func setupLayers(){
        drawLayer.frame = view.bounds
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        
        previewLayer.frame = view.bounds
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspect
        view.layer.insertSublayer(previewLayer, atIndex: 0)
    }
    
    // MARK - 懒加载
    lazy var drawLayer:CALayer = CALayer()
    
    lazy var previewLayer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    
    lazy var session:AVCaptureSession = AVCaptureSession()
    
    lazy var inputDevice:AVCaptureDeviceInput? = {
       let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do{
            return try AVCaptureDeviceInput(device: device)
        }catch{
            print(error)
            return nil
        }
    }()
    
    lazy var outputData:AVCaptureMetadataOutput = AVCaptureMetadataOutput()

}
